"use strict";
var _uid, _node2, _latlon, _selNode, _inited;
var $structure_overall, $structure_station, $selectPeriod, $currentYear, _checkStatEnum;

function init() {
	_uid = vw_static.getCookie(window.location.host);
	$structure_overall = $('#structure_overall');
	$structure_station = $('#structure_station');
	$selectPeriod = $('#selectPeriod');
	$currentYear = $('#currentYear');
	_selNode = null;
	_inited = false;

	var subFunction = [
		'<ul class="nav nav-pills navbar-left" style="margin: 10px 0 0 100px;">',
		'	{{#items}}<li class="{{class}}" style="margin-left: 10px;">',
		'		<a href="#{{tab}}" class="btn btn-custom" data-toggle="tab"><i class="fa fa-{{icon}}"></i> {{name}}</a>',
		'	</li>{{/items}}',
		'</ul>'
	].join('');

	require(['mustache'], function(mustache) {
		$('#vw-navbar-custom').append(mustache.render(subFunction, {
			"items": [{
				"tab": "tab_overall",
				"class": "active",
				"icon": "database",
				"name": "分报表统计"
			}, {
				"tab": "tab_station",
				"icon": "sitemap",
				"name": "分调查对象统计"
			}]
		})).on('click', 'a', function() {
			switch($(this).attr("href")) {
				case "#tab_overall":
					getCheckStat("数据状态");
					InitTab_Overall();
					break;
				case "#tab_station":
					getCheckStat("status");
					InitTab_Station();
					break;
			}
		});
	});
	getyear();
	getCheckStat("数据状态");
	//	InitTab_Overall();
	initPeriod();
}

function initPeriod() {
	$selectPeriod.select2({
		placeholder: "请选择...",
		language: "zh-CN"
	});

	vw_common.customAjax({
		url: VW_INTERFACE.WEBSERVICE.CollectionManage("GetPeriod"),
		type: "get",
		dataType: "json",
	}, function(e) {
		for(var i = 0; i < e.data.length; i++) {
			$selectPeriod.append('<option value="' + e.data[i].id + '">' + e.data[i].text + '</option>');
		};
		$selectPeriod.on('select2:select', function(e) {
			_inited = false;
			InitTab_Overall();
		});
		$selectPeriod.val(e.data[0].id).trigger('select2:select');
	});
}

function InitTab_Overall() {
	$selectPeriod.parent().show();
	//	$selectPeriod.parent().css('right', "300px");
	$currentYear.parent().css('right', "190px");
	$structure_overall.vw_structure('destroy').vw_structure({
		searchtree: {
			selectChildNodeOnly: true,
			onTreeSelected: function(node) {
				_selNode = node;
				if(_inited) {
					console.log("onTreeSelected")
				}
			}
		},
		edittable: {
			showImportData: false,
			showNewData: false,
			showErrorlog: false,
			showEdit: false,
			showExport: true,
			columnFormatter: _columnFormatter,
		},
		map: {
			fillColors: ["#767676", "#0000ff", "#ffff00", "#00ff00", "#ff0000", "#000000"],
		},
		onTabShown: function(e) {
			_inited = (e == "map");
			fn_locate(_selNode);
		},
		interfaceAddress: VW_INTERFACE.WEBSERVICE.TaskMonitor,
		extrapara: {
			"userID": _uid,
			"period": $selectPeriod.val(),
			"year": _year.currentYear
		},

	});
}

function fn_locate(node) {
	$structure_overall.vw_structure('getMap').append("<div id='mapMask'><div id='mapMaskText'>正在加载数据，请稍候。。。</div></div>")
	$("#mapMask").css({
		"position": "absolute",
		"top": "0",
		"left": "0",
		"width": "100%",
		"height": "100%",
		"background": "#FFFFFF",
		"opacity": "0.3",
		"z-index": "999999"
	});
	$("#mapMaskText").css({
		"position": "absolute",
		"top": "50%",
		"left": "35%",
		"font-size": "28px"
	});

	vw_common.customAjax({
		url: VW_INTERFACE.WEBSERVICE.TaskMonitor('GetObject'),
		type: 'GET',
		dataType: 'json',
		data: {
			"table": node.id,
			"period": $selectPeriod.val(),
			"year": _year.currentYear
		},
	}, function(e) {

		e.data.head.themes = [];
		$.each(e.data.head.columns, function(k, val) {
			e.data.head.themes.push(k);
		});
		vw_common.customAjax({
			url: VW_INTERFACE.WEBSERVICE.TableManage('GetTableData'),
			type: "GET",
			dataType: "json",
			data: {
				table: "TB_BIZ_SURVEY_STATUS"
			}
		}, function(ee) {
			var dic = {};
			$.each(ee.data, function(k, val) {
				dic[val[0]] = {
					id: k,
					text: val[1]
				};
			});
			e.data.head.enums.dic = dic;
			$structure_overall.vw_structure('getMap').vw_map('refresh').vw_map("drawPolygon", e.data, true, {
				color: "#FFFACD",
				weight: 1
			});

			$("#mapMask").remove();
		});
	});
}

function InitTab_Station() {
	$selectPeriod.parent().hide();
	$currentYear.parent().css('right', "30px");
	var custom = [
		'<div class="row">',
		'	<div class="col-md-12">',
		'		<button type="button" id="btn_prompt" class="btn btn-danger pull-left" style="margin:0 10px 5px 0"><i class="fa fa-bell-o"></i>  催报</button>',
		'		<button type="button" id="btn_export" class="btn btn-primary pull-left" style="margin:0 10px 5px 0"><i class="fa fa-download"></i>  导出</button>',
		'		<div id="statmsg" class="pull-right" style="padding: 5px 10px;"></div>',
		'		<table id="vw-treetable"></table>',
		'	</div>',
		'</div>'
	].join('');

	$structure_station.vw_structure('destroy').vw_structure({
		showEdittable: false,
		customTab: custom,
		searchtree: {
			showEdit: false,
			onTreeSelected: function(node) {
				_node2 = node;
				ReadStationData($('#vw-treetable'), $('#statmsg'), _node2)
			}
		},
		interfaceAddress: VW_INTERFACE.WEBSERVICE.TaskMonitor,
		treeDataURL: 'GetSurveyData',
		onInitialized: function() {
			$('#btn_prompt').on('click', function() {
				prompt(_node2);
			});
			$('#btn_export').on('click', function() {
				downloadTable($('#vw-treetable')[0], _node2.text);
			});
		}
	});
}

function ReadStationData($treetable, $StatMsg, node) {
	require(["bootstrap.table-cn", 'bootstrap.table.treegrid'], function() {
		vw_common.customAjax({
			url: VW_INTERFACE.WEBSERVICE.TaskMonitor('LoadTreeData'),
			type: 'GET',
			dataType: 'json',
			data: {
				"table": node.id,
				"type": 2,
				//				"period": $selectPeriod.val(),
				"year": _year.currentYear
			},
		}, function(e) {
			$StatMsg.text("合计：" + e.summary);
			$treetable.bootstrapTable('destroy').bootstrapTable({
				data: e.data,
				columns: [{
						field: 'name',
						title: '表名称'
					},
					{
						field: 'status',
						title: '数据状态',
						align: 'center',
						formatter: _columnFormatter['status'],
					},
					{
						field: 'username',
						align: 'center',
						title: '上报人'
					},
					{
						field: 'time',
						align: 'center',
						title: '上报时间'
					}
				],
				treeShowField: "name",
				idField: "id",
				parentIdField: "pid",
				height: $(window).height() - 180,
			})

			$treetable.treegrid({
				initialState: 'expanded',
				treeColumn: 0,
				expanderExpandedClass: 'glyphicon glyphicon-chevron-down',
				expanderCollapsedClass: 'glyphicon glyphicon-chevron-right'
			})

			$treetable.find('td:nth-child(1) span').addClass('pull-left');
			$treetable.find('td:nth-child(1) div').addClass('pull-left');
		});
	});
}

function prompt(node) {
	vw_common.customAjax({
		url: VW_INTERFACE.WEBSERVICE.TaskMonitor('Prompt'),
		type: 'GET',
		dataType: 'json',
		data: {
			"table": node.id,
			"type": 2,
			"year": _year.currentYear
		},
	}, function(e) {
		$.Notify({
			caption: "提示",
			content: "已向调查员发送站内信催报",
			type: "info"
		});
	});
}

function downloadTable(table, filename) {
	require(['xlsx', 'FileSaver'], function() {
		var workbook = XLSX.utils.table_to_book(table);
		var wbout = XLSX.write(workbook, {
			bookType: 'xlsx',
			bookSST: false,
			type: 'binary'
		});

		saveAs(new Blob([s2ab(wbout)], {
			type: ""
		}), filename + ".xlsx");

		function s2ab(s) {
			var buf = new ArrayBuffer(s.length);
			var view = new Uint8Array(buf);
			for(var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
			return buf;
		}
	})
}